package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @Author: 李壮
 * @CreateTime: 2025-05-13
 * @Version: 1.0
 */


public class JwtUtil {

    private static long tokenExpiration = 60 * 60 * 1000L;
    private static SecretKey tokenSingKey =
            Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    //创建token
    public static String createToken(Long userId,String username){
        String token = Jwts.builder()
                .setSubject("USER_INFO")
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                .claim("userId",userId)
                .claim("userName",username)
                .signWith(tokenSingKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        System.out.println(token);
        return token;
    }

    //解析token
    public static Claims parseToken(String token){

        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(tokenSingKey)
                    .build()
                    .parseClaimsJws(token);

            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED.getMessage(),ResultCodeEnum.PARAM_ERROR.getCode());
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID.getMessage(),ResultCodeEnum.TOKEN_INVALID.getCode());
        }
    }


}
